//
//  XMMenuView.m
//  XiaoMiao
//
//  Created by 23 on 2017/11/13.
//  Copyright © 2017年 smallyou. All rights reserved.
//

#import "XMMenuView.h"

@interface XMMenuView ()

#pragma mark - 标志
/**上一个选中的按钮*/
@property(nonatomic,weak) UIButton *lastSelectedButton;

@end

@implementation XMMenuView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        
        self.backgroundColor = [UIColor whiteColor];
        
    }
    return self;
}

- (void)setTitles:(NSArray *)titles
{
    _titles = titles;
    
    
    for (int i = 0; i < titles.count; i++) {
        
        NSString *title = titles[i];
        
        UIButton *button = [[UIButton alloc]init];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitleColor:kRGBColor(37, 179, 252) forState:UIControlStateSelected];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14.0];
        button.tag = 2000 + i;
        [button addTarget:self action:@selector(menuDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:button];
    }
    
    
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    int i = 0;
    CGFloat margin = 20;
    CGFloat width = (self.bounds.size.width - 2 * margin) / self.titles.count;
    CGFloat height = self.bounds.size.height - 1;
    for (UIView *view in self.subviews) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            view.frame = CGRectMake(margin + i * width, 0, width, height);
            
            
            i++;
            
        }
    }
    
    
}



#pragma mark - 事件监听

- (void)menuDidClick:(UIButton *)button
{
    //处理按钮的选中状态
    self.lastSelectedButton.selected = NO;
    button.selected = YES;
    self.lastSelectedButton = button;
    
    //记录当前选中的索引
    _selectedIndex = button.tag - 2000;
    
    //回调
    if ([self.delegate respondsToSelector:@selector(menuView:didMenuBtnClicked:)]) {
        [self.delegate menuView:self didMenuBtnClicked:button];
    }
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    _selectedIndex = selectedIndex;
    
    //选中对应的按钮
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIButton class]] && (view.tag == selectedIndex + 2000)) {
            [self menuDidClick:(UIButton *)view];
        }
    }
    
}


@end
